package com.wing.sell.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.model.entity.Attachment;
import com.wing.common.model.entity.ExternalProduct;
import com.wing.common.model.request.AttachmentForm;
import com.wing.common.model.request.ExternalProductForm;
import com.wing.common.service.AttachmentService;
import com.wing.common.service.ExternalProductService;
import com.wing.dict.model.entity.DictLabel;
import com.wing.product.model.entity.ProductType;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductTypeService;
import com.wing.product.service.ProductUnitService;
import com.wing.sell.dao.CustomerProductCatalogDao;
import com.wing.sell.model.entity.CustomerCategory;
import com.wing.sell.model.entity.CustomerProductCatalog;
import com.wing.sell.model.entity.CustomersInfo;
import com.wing.sell.model.request.CustomerProductCatalogForm;
import com.wing.sell.model.response.CustomerProductCatalogVO;
import com.wing.sell.service.CustomerProductCatalogService;
import com.wing.sell.service.CustomersInfoService;
import com.wing.web.excel.CustomerProductCatalogExcelIn;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.wing.common.model.entity.ExternalProduct.Type.customer;

/**
 * 客户产品目录-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CustomerProductCatalogServiceImpl extends ServiceImpl<CustomerProductCatalogDao, CustomerProductCatalog> implements CustomerProductCatalogService {

    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private ExternalProductService externalProductService;
    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private ProductTypeService productTypeService;

    @Autowired
    private CustomersInfoService customersInfoService;

    @Autowired
    private ProductUnitService productUnitService;

    @Autowired
    private CustomerProductCatalogService catalogService;


    private final String tableName = "com_external_product";
    @Autowired
    private CustomerProductCatalogService customerProductCatalogService;

    @Override
    public int add(CustomerProductCatalogForm customerProductCatalogForm) {

        //校验

        CustomerProductCatalog customerProductCatalog = new CustomerProductCatalog();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(CustomerProductCatalog.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(customerProductCatalogForm, customerProductCatalog, copyOptions);

        return baseMapper.insert(customerProductCatalog);
    }

    @Override
    public List<CustomerProductCatalogVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<CustomerProductCatalogVO> pageList4app(Page page, Map<String, Object> params) {
        List<CustomerProductCatalogVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public CustomerProductCatalogVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public void addProduct(CustomerProductCatalogForm form) {
        //添加外部产品信息
        List<ExternalProductForm> externalList = form.getExternalProductForm();
        if (CollectionUtils.isNotEmpty(externalList)) {
            externalList.forEach(info -> {
                //添加外部产品 1
                ExternalProduct externalProduct = new ExternalProduct();
                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(ExternalProduct.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(info, externalProduct, copyOptions);
                externalProduct.setCreatorName(JwtUtils.getLoginUsername());
                externalProduct.setCreator(JwtUtils.getLoginUserId());
                externalProduct.setCreateTime(LocalDateTime.now());
                externalProduct.setName(info.getCusProductName());
                externalProduct.setCode(info.getCusSkuCode());
                externalProduct.setSpec(info.getCusProductSpec());
                externalProduct.setType(customer);
                externalProductService.save(externalProduct);

                //添加客户产品绑定关系
                CustomerProductCatalog catalog = new CustomerProductCatalog();
                catalog.setCustomerId(form.getCustomerId());
                catalog.setContactId(form.getContactId());
                catalog.setExtProductId(externalProduct.getId());
                catalog.setSkuCode(externalProduct.getCode());
                catalog.setCusProductSpec(externalProduct.getSpec());
                catalog.setCusProductName(externalProduct.getName());
                catalog.setCusProductCode(externalProduct.getCode());
                catalog.setCusProductType(info.getCusProductType());
                catalog.setCreatorName(JwtUtils.getLoginUsername());
                catalog.setCreator(JwtUtils.getLoginUserId());
                catalog.setCreateTime(LocalDateTime.now());
                catalogService.save(catalog);

                //添加附件
                AttachmentForm attachmentForm = new AttachmentForm();
                if (StrUtil.isNotEmpty(info.getEnclosure())) {
                    Attachment attachment = new Attachment();
                    CopyOptions copyOptionsTwo = CopyOptions.create()
                            .setEditable(Attachment.class)
                            .setIgnoreError(true)
                            .setIgnoreNullValue(true);
                    BeanUtil.copyProperties(attachmentForm, attachment, copyOptionsTwo);
                    attachment.setCreatorName(JwtUtils.getLoginUsername());
                    attachment.setCreator(JwtUtils.getLoginUserId());
                    attachment.setCreateTime(LocalDateTime.now());
                    attachment.setTableName(tableName);
                    attachment.setTableId(externalProduct.getId());
                    attachment.setAttachment(info.getEnclosure());
                    attachment.setName(info.getEnclosureName());
                    attachmentService.save(attachment);
                }
            });
        }

//        //添加sku
//        List<ProductDetailForm> detailFormList = customerProductCatalogForm.getProductDetailForm();
//        ProductDetailForm productDetailForm = new ProductDetailForm();
//        //判断SKU编号是否有重复
//        ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(detailFormList.get(0).getSkuCode());
//        if(productDetailVO!=null){
//            throw new BusinessException("产品SKU编码重复！");
//        }
//
//        //判断商品规格是否有重复
//        for(int i=0; i < detailFormList.size(); i++){
//            productDetailForm.setSkuCode(detailFormList.get(i).getSkuCode());
//            productDetailForm.setSkuName(detailFormList.get(i).getSkuName());
//            productDetailForm.setOldSpecCode(detailFormList.get(i).getOldSpecCode());
//            productDetailForm.setUnitId(detailFormList.get(i).getUnitId());
//            productDetailForm.setPackId(detailFormList.get(i).getPackId());
//            productDetailForm.setSkuSpec(detailFormList.get(i).getSkuSpec());
//            productDetailForm.setSkuSpecValue(detailFormList.get(i).getSkuSpecValue());
//            productDetailForm.setSkuSpecValueNames(detailFormList.get(i).getSkuSpecValueNames());
//            productDetailForm.setProductId(detailFormList.get(i).getProductId());
//            productDetailForm.setProductTypeId(detailFormList.get(i).getProductTypeId());
//            productDetailForm.setProductCategoryId(detailFormList.get(i).getProductCategoryId());
//            productDetailForm.setRemark(detailFormList.get(i).getRemark());
//            productDetailForm.setWeightNumber(detailFormList.get(i).getWeightNumber());
//        }
//        productDetailService.add(productDetailForm);
    }

    @Override
    public void addProductOutApi(CustomerProductCatalogForm form) {
        //添加外部产品信息
        List<ExternalProductForm> externalList = form.getExternalProductForm();
        if (CollectionUtils.isNotEmpty(externalList)) {
            externalList.forEach(info -> {
                //添加外部产品 1
                ExternalProduct externalProduct = new ExternalProduct();
                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(ExternalProduct.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(info, externalProduct, copyOptions);
                externalProduct.setCreatorName(JwtUtils.getLoginUsername());
                externalProduct.setCreator(JwtUtils.getLoginUserId());
                externalProduct.setCreateTime(LocalDateTime.now());
                externalProduct.setName(info.getCusProductName());
                externalProduct.setCode(info.getCusSkuCode());
                externalProduct.setSpec(info.getCusProductSpec());
                externalProduct.setType(customer);
                externalProductService.save(externalProduct);
            });
        }
    }

    @Override
    public CustomerProductCatalogVO getInfoByCode(String code) {
        return baseMapper.getInfoByCode(code);
    }

    /**
     * 查询产品明细
     *
     * @param id
     * @return
     */
    @Override
    public CustomerProductCatalogForm getDetail(Long id) {
        CustomerProductCatalogForm customerProductCatalogForm = new CustomerProductCatalogForm();
        //查询产品信息
        CustomerProductCatalog catalog = baseMapper.selectById(id);
        //获取所有的类型
        List<ProductType> productTypes = productTypeService.list();
        if (ObjectUtil.isNotEmpty(catalog)) {
            List<ExternalProductForm> list = new ArrayList<>();
            BeanUtil.copyProperties(catalog, customerProductCatalogForm, true);
            ExternalProduct byId = this.externalProductService.getById(catalog.getExtProductId());
            if (ObjectUtil.isNotEmpty(byId)) {
                ExternalProductForm form = new ExternalProductForm();
                BeanUtil.copyProperties(byId, form, true);
                form.setCusSkuCode(byId.getCode());
                form.setCusProductSpec(byId.getSpec());
                form.setCusProductName(byId.getName());
                for (ProductType productType : productTypes) {
                    if (ObjectUtil.isNotEmpty(byId.getProTypeId()) && productType.getId().equals(byId.getProTypeId())) {
                        form.setProTypeName(productType.getName());
                    }
                }
                QueryWrapper<Attachment> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("table_name", tableName);
                queryWrapper.eq("table_id", catalog.getExtProductId());
                Attachment one = this.attachmentService.getOne(queryWrapper);
                if (ObjectUtil.isNotEmpty(one)) {
                    form.setEnclosure(one.getAttachment());
                    form.setEnclosureName(one.getName());
                }
                form.setCusProductType(catalog.getCusProductType());
                list.add(form);
            }
            return customerProductCatalogForm.setExternalProductForm(list);
        }
        return null;
    }

    /**
     * 修改客户产品
     *
     * @param customerProductCatalogForm
     * @return
     */
    @Override
    @Transactional
    public boolean updateInfo(CustomerProductCatalogForm customerProductCatalogForm) {
        //修改客户产品
        CustomerProductCatalog customerProductCatalog = this.getById(customerProductCatalogForm.getId());
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(CustomerProductCatalog.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(customerProductCatalogForm, customerProductCatalog, copyOptions);
        customerProductCatalog.setUpdateTime(LocalDateTime.now());
        customerProductCatalog.setModifier(JwtUtils.getLoginUserId());
        if (CollectionUtils.isNotEmpty(customerProductCatalogForm.getExternalProductForm())){
            customerProductCatalog.setCusProductType(customerProductCatalogForm.getExternalProductForm().get(0).getCusProductType());
        }
        customerProductCatalog.setModifierName(JwtUtils.getLoginUsername());
        boolean b = this.updateById(customerProductCatalog);
        if (b) {
            //修改外部产品
            ExternalProductForm form = customerProductCatalogForm.getExternalProductForm().get(0);
            ExternalProduct byId = this.externalProductService.getById(form.getId());
            BeanUtil.copyProperties(form, byId, true);
            byId.setUpdateTime(LocalDateTime.now());
            byId.setSpec(form.getCusProductSpec());
            byId.setCode(form.getCusSkuCode());
            byId.setName(form.getCusProductName());
            byId.setModifier(JwtUtils.getLoginUserId());
            byId.setModifierName(JwtUtils.getLoginUsername());
            boolean exb = this.externalProductService.updateById(byId);
            if (exb) {
                //删除图片信息 如果有 在插入
                QueryWrapper<Attachment> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("table_name", tableName);
                queryWrapper.eq("table_id", customerProductCatalog.getId());
                attachmentService.remove(queryWrapper);

                if (StrUtil.isNotEmpty(form.getEnclosure())) {
                    Attachment attachment = new Attachment();
                    attachment.setCreatorName(JwtUtils.getLoginUsername());
                    attachment.setCreator(JwtUtils.getLoginUserId());
                    attachment.setCreateTime(LocalDateTime.now());
                    attachment.setTableName(tableName);
                    attachment.setTableId(customerProductCatalog.getId());
                    attachment.setAttachment(form.getEnclosure());
                    attachment.setName(form.getEnclosureName());
                    boolean save = attachmentService.save(attachment);
                    if (save) {
                        return true;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public Long getOutProductId(String code) {
        QueryWrapper<ExternalProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        ExternalProduct one = this.externalProductService.getOne(queryWrapper);
        return one!=null?one.getId():null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importExcel(List<CustomerProductCatalogExcelIn> list) {

        List<CustomersInfo> cataList = customersInfoService.list();

        List<ProductUnitInfo> infoList = productUnitService.getUnitDisInfo();
        List<ProductType> productTypes = productTypeService.list();
        Map<String, Long> typeList = productTypes.stream().collect(Collectors
                .toMap(ProductType::getName, ProductType::getId));

        Map<String, Long> unitList = infoList.stream().collect(Collectors
                .toMap(ProductUnitInfo::getName, ProductUnitInfo::getId));

        Map<String, Long> cusInfos = cataList.stream().filter(customersInfo -> StrUtil.isNotEmpty(customersInfo.getCustomerName())).collect(Collectors
                .toMap(CustomersInfo::getCustomerName, CustomersInfo::getId));
        //1. 插入com_external_product表
        for (CustomerProductCatalogExcelIn excelIn : list) {
            ExternalProduct externalProduct = new ExternalProduct();
            externalProduct.setCode(excelIn.getCusProductCode());
            externalProduct.setName(excelIn.getCusProductName());
            externalProduct.setType(customer);
            externalProduct.setSpec(excelIn.getCusProductSpec());
            externalProduct.setCreateTime(LocalDateTime.now());
            externalProduct.setCreator(JwtUtils.getLoginUserId());
            externalProduct.setCreatorName(JwtUtils.getLoginUsername());
            if (StrUtil.isNotEmpty(excelIn.getHasPack())){
                externalProduct.setHasPack("是".equals(excelIn.getHasPack()));
            }
            externalProduct.setPackInstructions(excelIn.getPackInstructions());
            if (StrUtil.isNotEmpty(excelIn.getHasTreatment())){
                externalProduct.setHasPack("是".equals(excelIn.getHasTreatment()));
            }
            externalProduct.setTreatmentInstructions(excelIn.getTreatmentInstructions());
            if (StrUtil.isNotEmpty(excelIn.getCusProductType())){
                externalProduct.setProTypeId(typeList.get(excelIn.getCusProductType()));
            }
            if (StrUtil.isNotEmpty(excelIn.getCusProductUnit())){
                externalProduct.setProUnitId(unitList.get(excelIn.getCusProductUnit()));
            }
            boolean save = externalProductService.save(externalProduct);
            if (save) {
                //1. 插入sel_customer_product_catalog表
                CustomerProductCatalog customerProductCatalog = new CustomerProductCatalog();

                customerProductCatalog.setCustomerId(cusInfos.get(excelIn.getCustomerName()));
                customerProductCatalog.setExtProductId(externalProduct.getId());
                if (StrUtil.isNotEmpty(excelIn.getCusProductType())){
                    customerProductCatalog.setCusProductType(typeList.get(excelIn.getCusProductType()).toString());
                }
                if (StrUtil.isNotEmpty(excelIn.getCusProductUnit())){
                    customerProductCatalog.setCusProductUnit(unitList.get(excelIn.getCusProductUnit()).toString());
                }
                customerProductCatalog.setCusProductSpec(excelIn.getCusProductSpec());
                customerProductCatalog.setCusProductName(excelIn.getCusProductName());
                customerProductCatalog.setCusProductCode(excelIn.getCusProductCode());
                customerProductCatalog.setInSkuCode(null);
                customerProductCatalog.setSkuCode(excelIn.getCusProductCode());
                customerProductCatalog.setCreateTime(LocalDateTime.now());
                customerProductCatalog.setCreator(JwtUtils.getLoginUserId());
                customerProductCatalog.setCreatorName(JwtUtils.getLoginUsername());
                customerProductCatalogService.save(customerProductCatalog);
            }
        }
    }
}
